package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.LetterAnnexDao;
import com.leoman.dao.LetterAnnexSampleDao;
import com.leoman.entity.LetterAnnex;
import com.leoman.entity.LetterAnnexSample;
import com.leoman.service.LetterAnnexService;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * LetterAnnexServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:59.
 */
@Service
public class LetterAnnexServiceImpl implements LetterAnnexService {

    @Autowired
    private LetterAnnexDao letterAnnexDao;

    @Autowired
    private LetterAnnexSampleDao letterAnnexSampleDao;

    @Override
    public List<LetterAnnex> findAll() {
        return letterAnnexDao.findAll();
    }

    @Override
    public Page<LetterAnnex> find(int pageNum, int pageSize) {
        return letterAnnexDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<LetterAnnex> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public LetterAnnex getById(int id) {
        return letterAnnexDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        LetterAnnex letterAnnex = letterAnnexDao.findOne(id);

        QiNiuUtils.delete(letterAnnex.getCover());
        QiNiuUtils.delete(letterAnnex.getContent());

        letterAnnexDao.delete(id);
    }

    @Override
    public LetterAnnex create(LetterAnnex letterAnnex) {
        return letterAnnexDao.save(letterAnnex);
    }

    @Override
    public LetterAnnex update(LetterAnnex letterAnnex) {
        return letterAnnexDao.save(letterAnnex);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<LetterAnnex> pageByParams(final String name, final Integer type, final String num, Integer pageNum, Integer pageSize) {
        return letterAnnexDao.findAll(new Specification<LetterAnnex>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<LetterAnnex> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(name)) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
                }

                if (null != type) {
                    predicateList.add(cb.equal(root.get("type").as(Integer.class), type));
                }

                if (StringUtils.isNotBlank(num)) {
                    predicateList.add(cb.like(root.get("num").as(String.class), "%" + num + "%"));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    @Transactional
    public Integer save(Integer letterAnnexId, String name, Integer type, String num, String money, String description, MultipartRequest multipartRequest) {
        LetterAnnex letterAnnex = new LetterAnnex();
        try {
            MultipartFile cover = multipartRequest.getFile("cover");
            MultipartFile content = multipartRequest.getFile("content");

            if (null != letterAnnexId) {
                letterAnnex = letterAnnexDao.findOne(letterAnnexId);
                letterAnnex.setUpdateTime(System.currentTimeMillis());
            }

            letterAnnex.setType(type);
            if (null != cover && cover.getSize() > 0) {
                QiNiuUtils.delete(letterAnnex.getCover());
                letterAnnex.setCover(QiNiuUtils.upload(cover));
            } else {
                QiNiuUtils.delete(letterAnnex.getCover());
                letterAnnex.setCover("");
            }
            if (type == 1 && null != content && content.getSize() > 0) {
                QiNiuUtils.delete(letterAnnex.getContent());
                letterAnnex.setContent(QiNiuUtils.upload(content));
            } else {
                QiNiuUtils.delete(letterAnnex.getContent());
                letterAnnex.setContent("");
            }
            letterAnnex.setName(name);
            letterAnnex.setNum(num);
            letterAnnex.setMoney(Double.parseDouble(money));
            letterAnnex.setDescription(description);

            letterAnnexDao.save(letterAnnex);

            LetterAnnexSample letterAnnexSample;
            if (null != letterAnnexId) {
                letterAnnexSample = letterAnnexSampleDao.findOneByLetterAnnexId(letterAnnexId);
                if (null == letterAnnexSample) {
                    letterAnnexSample = new LetterAnnexSample();
                    letterAnnexSample.setLetterAnnexId(letterAnnexId);
                }
            } else {
                letterAnnexSample = new LetterAnnexSample();
                letterAnnexSample.setLetterAnnexId(letterAnnex.getId());
            }

            letterAnnexSample.setType(letterAnnex.getType());
            letterAnnexSample.setCover(letterAnnex.getCover());
            letterAnnexSample.setContent(letterAnnex.getContent());
            letterAnnexSample.setName(letterAnnex.getName());
            letterAnnexSample.setNum(letterAnnex.getNum());
            letterAnnexSample.setMoney(letterAnnex.getMoney());
            letterAnnexSample.setDescription(letterAnnex.getDescription());

            letterAnnexSampleDao.save(letterAnnexSample);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            QiNiuUtils.delete(letterAnnex.getCover());
            QiNiuUtils.delete(letterAnnex.getContent());
            return 0;
        }
    }

    @Override
    public List<LetterAnnex> findListByType(Integer type) {
        return letterAnnexDao.findListByType(type);
    }
}